package com.distributer.delayqueue.autoconfigure;

import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.zookeeper.server.ZooKeeperServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import com.distributer.delayqueue.zookeeper.LeaderManager;
import com.distributer.delayqueue.zookeeper.ServerNode;
import com.distributer.delayqueue.zookeeper.SimpleLeaderManager;
import com.distributer.delayqueue.zookeeper.ZookeeperListener;


@Configuration
@EnableConfigurationProperties(RegistryProperties.class)
@ConditionalOnClass(value = {ZooKeeperServer.class, CuratorFrameworkFactory.class})
@Order(Ordered.LOWEST_PRECEDENCE + 50)
public class LeaderAutoConfiguration {

    @Autowired
    private RegistryProperties registryProperties;
    @Value("${server.port}")
	private String port;
    @Value("${spring.application.name}")
	private String applicationName;
    
    @Bean
    @Autowired
    @ConditionalOnMissingBean
    public LeaderLatchListener leaderLatchListenerImpl(RedisQueueImpl redisQueueImpl) {
    	ZookeeperListener listener = new ZookeeperListener();
    	listener.setQueue(redisQueueImpl,port);
        return listener;
    }

    @Bean(name = "simpleLeaderManager", initMethod = "init", destroyMethod = "stop")
    @Autowired
    @ConditionalOnMissingBean
    public LeaderManager leaderManager(LeaderLatchListener leaderLatchListener) {
        SimpleLeaderManager slm = new SimpleLeaderManager();
        slm.setRegisterProperties(registryProperties);
        slm.addListener(leaderLatchListener);
        ServerNode.NAMESPACE = registryProperties.getNamespace();
        slm.setServiceName(applicationName + ":" + port);
        return slm;
    }
}
